package com.ctgu.project02.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName TokenInterceptor
 * @Author Alex2
 * @Date 2025/2/26 11:02
 **/
@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Qualifier("redisTemplateForObject")
    private final RedisTemplate<String, Object> redisTemplateForObject;

    @Autowired
    public TokenInterceptor(RedisTemplate<String, Object> redisTemplateForObject) {
        this.redisTemplateForObject = redisTemplateForObject;
    }

    private final String REDIS_KEY_LOGIN_TOKEN = "login:token:";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if(request.getMethod().equals("OPTIONS")){
            return true;
        }
        System.out.println("url : " + request.getRequestURI() + " - token : " + token + " - Method : " + request.getMethod());
        if (token == null) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }
        Map<Object, Object> userMap = redisTemplateForObject.opsForHash().entries(REDIS_KEY_LOGIN_TOKEN + token);
        if (userMap.isEmpty()) {
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            errorResponse(response);
            return false;
        }
        return true;
    }

    public void errorResponse(HttpServletResponse response) throws Exception {
        HashMap<String, Object> map = new HashMap<>();
        map.put("msg", "token无效");
        map.put("code", HttpServletResponse.SC_UNAUTHORIZED);
        map.put("data", null);
        String json = new ObjectMapper().writeValueAsString(map);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().println(json);
    }
}